package android.slc.popup.fast;

import android.app.Dialog;
import android.content.Context;
import android.slc.popup.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;

/**
 * 加载对话框
 */
public class SimpleLoadingBuilder {
    private final Context mContext;
    private final Dialog mLoadingDialog;
    private View mLoadingView;
    private CharSequence mMessage;
    private int mMaxWidth, mMaxHeight;


    public SimpleLoadingBuilder(@NonNull Context context) {
        this(context, 0);
    }

    public SimpleLoadingBuilder(@NonNull Context context, @StyleRes int themeResId) {
        super();
        mContext = context;
        mLoadingDialog = new Dialog(context, themeResId);
    }


    public SimpleLoadingBuilder setView(int layoutResId) {
        return setView(LayoutInflater.from(mContext).inflate(layoutResId, null));
    }

    public SimpleLoadingBuilder setView(View view) {
        this.mLoadingView = view;
        return this;
    }

    public SimpleLoadingBuilder setMessage(int messageId) {
        return setMessage(mContext.getString(messageId));
    }

    public SimpleLoadingBuilder setMessage(@Nullable CharSequence message) {
        this.mMessage = message;
        return this;
    }

    public SimpleLoadingBuilder setMaxHeight(int mMaxHeight) {
        this.mMaxHeight = mMaxHeight;
        return this;
    }

    public SimpleLoadingBuilder setMaxWidth(int mMaxWidth) {
        this.mMaxWidth = mMaxWidth;
        return this;
    }

    public Dialog create() {
        if (mLoadingView == null) {
            mLoadingView = LayoutInflater.from(mContext).inflate(R.layout.slc_popup_def_loading, null);
        }
        TextView messageTextView = mLoadingView.findViewById(android.R.id.message);
        if (messageTextView != null) {
            messageTextView.setText(mMessage);
        }
        mLoadingDialog.setContentView(mLoadingView);
        mLoadingDialog.getWindow().getDecorView().addOnLayoutChangeListener((View v, int left, int top, int right, int bottom,
                                                                             int oldLeft, int oldTop,
                                                                             int oldRight, int oldBottom) -> {
            ViewGroup.LayoutParams contentViewLayoutParams = v.getLayoutParams();
            if (contentViewLayoutParams != null) {
                if (mMaxWidth != 0 && v.getWidth() > mMaxWidth) {
                    contentViewLayoutParams.width = mMaxWidth;
                }
                if (mMaxHeight != 0 && v.getHeight() > mMaxHeight) {
                    contentViewLayoutParams.height = mMaxHeight;
                }
                v.setLayoutParams(contentViewLayoutParams);
            }
        });
        return mLoadingDialog;
    }
}